﻿/* 
 *  <copyright file="TriggerResponseBase.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System;
using System.Collections.Generic;
using SobrietyEngine.Guids;
using SobrietyEngine.Components;
using SobrietyEngine.Events;
using SobrietyEngine.Actor;

namespace SobrietyEngine.Components.Trigger.Response
{
    public class TriggerResponseBase : BaseComponent, IComponent, IEventListener
    {
        //the trigger we listen for
        public String[] MyTriggers { get; set; }


        public TriggerResponseBase()
            : base()
        {
        }

        public TriggerResponseBase(String[] triggerActor)
            : base()
        {
            MyTriggers = triggerActor;
        }

        public virtual void RegisterEventListeners()
        {
            //add controller listener events
            Actor.EventRouter.AddEventListener(typeof(Events.Component.Triggered), this);
        }

        public virtual void UnregisterEventListeners()
        {
            //remove controller listener events
            Actor.EventRouter.RemoveEventListener(this);
        }

        override public Boolean InitComponent()
        {
            RegisterEventListeners();
            return true;
        }

        public void HandleEvent(Event e)
        {
            Events.Component.Triggered ted = (Events.Component.Triggered)e.Data;
            ITrigger trigger = (ITrigger)ted.Trigger;
            if (trigger == null)
                return;

            foreach(String s in MyTriggers)
                if(trigger.TriggerName == s )
                    Trigger(trigger, ted.TriggeredBy);
        }

        public new void Remove()
        {
            UnregisterEventListeners();
        }

        public virtual void Trigger( ITrigger trigger, CGuid byWho)
        {
            IActor ta = ((IComponent)trigger).Actor;
            ITrigger toc = ta.Get<ITrigger>();
            Logging.Logger.GetSingleton().WriteDebug(this, "DebugTigger: trigger '" + ta.Guid + "' with val '"+toc.TriggerValue.ToString()+"' triggered by '" + byWho + "'");
        }

        public virtual void Trigger(CGuid byWho)
        {
            Logging.Logger.GetSingleton().WriteDebug(this, "DebugTigger: triggered by '" + byWho + "'");
        }
    }
}
